import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('@/layout/index.vue'),
      redirect: '/dashboard',
      meta: { requiresAuth: true },
      children: [
        {
          path: '/dashboard',
          name: 'Dashboard',
          component: () => import('@/views/Dashboard.vue'),
          meta: { title: '仪表盘', icon: 'Dashboard' }
        },
        {
          path: '/system',
          name: 'System',
          component: () => import('@/views/system/index.vue'),
          meta: { title: '系统管理', icon: 'Setting' },
          children: [
            {
              path: '/system/users',
              name: 'UserManagement',
              component: () => import('@/views/system/UserManagement.vue'),
              meta: { title: '用户管理', icon: 'User' }
            },
            {
              path: '/system/roles',
              name: 'RoleManagement',
              component: () => import('@/views/system/RoleManagement.vue'),
              meta: { title: '角色管理', icon: 'UserFilled' }
            },
            {
              path: '/system/permissions',
              name: 'PermissionManagement',
              component: () => import('@/views/system/PermissionManagement.vue'),
              meta: { title: '权限管理', icon: 'Key' }
            },
            {
              path: '/system/menus',
              name: 'MenuManagement',
              component: () => import('@/views/system/MenuManagement.vue'),
              meta: { title: '菜单管理', icon: 'Menu' }
            }
          ]
        },
        {
          path: '/monitor',
          name: 'Monitor',
          component: () => import('@/views/monitor/index.vue'),
          meta: { title: '运维监控', icon: 'Monitor' },
          children: [
            {
              path: '/monitor/system',
              name: 'SystemMonitor',
              component: () => import('@/views/monitor/SystemMonitor.vue'),
              meta: { title: '系统监控', icon: 'Cpu' }
            },
            {
              path: '/monitor/logs',
              name: 'LogManagement',
              component: () => import('@/views/monitor/LogManagement.vue'),
              meta: { title: '日志管理', icon: 'Document' }
            }
          ]
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.meta.requiresAuth !== false && !authStore.isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router
